import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout/Layout.vue'
import Login from '../views/Login.vue'
import Home from '../views/Home/Home.vue'

Vue.use(VueRouter)

// 默认路由
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: '/home',
        name: 'Home',
        component: Home
      }
    ]
  }
]

// 动态路由
const asyncRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: Login,
    visible: false
  },
  // 首页
  {
    path: '/layout',
    name: 'Layout',
    component: Layout,
    redirect: '/home',
    visible: true,
    meta: { title: '后台⾸⻚', icon: 'icon-icon_home' },
    children: [
      {
        path: '/home',
        name: 'Home',
        component: Home
      }
    ]
  },
  // 订单管理
  {
    path: '/order',
    name: 'Layout',
    component: Layout,
    redirect: '/order/order-list',
    visible: true,
    meta: { title: '订单管理', icon: 'icon_orderedlist', role: ['super'] },
    children: [
      {
        path: '/order/orderlist',
        component: () => import('@/views/Order/OrderList.vue'),
        meta: { title: '订单列表' }
      },
      {
        path: '/order/order-edit',
        component: () => import('../views/Order/OrderEdit.vue'),
        meta: { title: '订单编辑' }
      }
    ]
  },
  // 商品管理
  {
    path: '/goods',
    name: 'Layout',
    component: Layout,
    redirect: '/goods/goods-list',
    visible: true,
    meta: { title: '商品管理', icon: 'icon-shangpin', role: ['super', 'normal'] },
    children: [
      {
        path: '/goods/goods-list',
        component: () => import('../views/Goods/GoodsList.vue'),
        meta: { title: '商品列表' }
      },
      {
        path: '/goods/goods-add',
        component: () => import('../views/Goods/GoodsAdd.vue'),
        meta: { title: '商品添加', role: ['super'] }
      },
      {
        path: '/goods/goodscate',
        component: () => import('../views/Goods/GoodsCate.vue'),
        meta: { title: '商品分类' }
      }
    ]
  },
  // 店铺管理
  {
    path: '/shop',
    name: 'Layout',
    component: Layout,
    visible: true,
    // redirect: '',
    meta: { title: '店铺管理', icon: 'icon-dianpu' },
    children: [
      {
        path: '',
        component: () => import('@/views/Shop/Shop.vue')
      }
    ]
  },
  // 帐户管理
  {
    path: '/account',
    name: 'Layout',
    component: Layout,
    visible: true,
    redirect: '/account/account-list',
    meta: { title: '账号管理', icon: 'icon_zhanghao', role: ['super', 'normal'] },
    children: [
      {
        path: '/account/account-add',
        component: () => import('../views/Account/AccountAdd.vue'),
        meta: { title: '账号添加', role: ['super'] }
      },
      {
        path: '/account/account-list',
        component: () => import('../views/Account/AccountList.vue'),
        meta: { title: '账号列表', role: ['super'] }
      },
      {
        path: '/account/pass-modify',
        meta: { title: '密码修改' },
        component: () => import('../views/Account/PassModify.vue')
      },
      {
        path: '/account/personal',
        meta: { title: '个⼈中⼼' },
        component: () => import('../views/Account/Personal.vue')
      }
    ]
  },
  // 销售统计
  {
    path: '/total',
    name: 'Layout',
    component: Layout,
    redirect: '/total/goodstotal',
    visible: true,
    meta: { title: '销售统计', icon: 'icon_tongji', role: ['super'] },
    children: [
      {
        path: '/total/goods-total',
        component: () => import('../views/Total/GoodsTotal.vue'),
        meta: { title: '商品统计' }
      },
      {
        path: '/total/order-total',
        component: () => import('../views/Total/OrderTotal.vue'),
        meta: { title: '订单统计' }
      }
    ]
  },
  // 错误路由
  {
    path: '/404',
    component: () => import('../views/error/404.vue')
  },
  {
    path: '*',
    redirect: '/404'
  }
]

const router = new VueRouter({
  routes
})
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

router.beforeEach((to, from, next) => {
  const isLogin = window.sessionStorage.getItem('token')
  // console.log(isLogin)
  if (isLogin || to.path === '/login') {
    next()
  } else {
    next({ path: '/login' })
  }
})

/**
 * created by xiongLing 2020-7-29
 * 封装动态路由
 * @description:判断当前路由对象有没有权限
 * @param {router}:当前对象
 * @param {role}:当前角色
 * @returns true:有权限的
 */

// 路由权限
function hasPermission(router, role) {
  // 如果路由中有meta，并且meta中有role，证明是配置了权限管理，需要做权限验证
  if (router.mate && router.meta.role) {
    return router.meta.role.includes(role)
  } else {
    // 没有配置权限，谁都可以访问
    // return false
    return true
  }
}

/**
 * created by xiongLing 2020-7-29
 * @description:计算出当前角色有权限访问的路由
 * @param {asyncRoutes}:动态路由
 * @param {role}:当前角色
 */
function calRoutes(asyncRoutes, role) {
  const accessRoutes = asyncRoutes.filter(router => {
    if (hasPermission(router, role)) {
      if (router.children && router.children.length) {
        router.children = calRoutes(router.children, role)
      }
      return true
    } else {
      return false
    }
  })
  return accessRoutes
}

/**
 * created by xiongLing 2020-7-29
 * @description:判断左侧菜单是否出现
 */
function isVisible(router, role) {
  if (router.visible) {
    return true
  } else {
    return false
  }
}
/**
 * @description:
 * @param {*} accessRoutes
 * @param {*} role
 */
function calcMenus(accessRoutes, role) {
  const arr = accessRoutes.filter(router => {
    if (isVisible(router, role)) {
      return true
    } else {
      return false
    }
  })
  return arr
}

/**
 * @description:根据角色，动态创建可以访问的路由
 */
export function createRoutes() {
  // 获取角色
  const role = window.sessionStorage.getItem('role')
  // 计算拿出有没有权限的路由
  const accessRoutes = calRoutes(asyncRoutes, role)
  // 动态添加路由
  router.addRoutes(accessRoutes)
  const menus = calcMenus(accessRoutes, role)
  console.log(menus)
  window.sessionStorage.setItem('menus', JSON.stringify(menus))
}
createRoutes()
export default router
